package cn.qidisoft.edu.hzjt.controller.zyc;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.qidisoft.core.common.log.LoggerAdapter;
import cn.qidisoft.core.common.log.LoggerAdapterFactory;
import cn.qidisoft.core.common.pagination.Page;
import cn.qidisoft.core.common.pagination.PaginationBean;
import cn.qidisoft.core.util.moffice.excel.ExpExcelUtil;
import cn.qidisoft.edu.hzjt.controller.BaseController;
import cn.qidisoft.edu.hzjt.exception.RPCException;
import cn.qidisoft.edu.hzjt.model.ResponseResult;
import cn.qidisoft.edu.hzjt.model.zyc.Department;
import cn.qidisoft.edu.hzjt.model.zyc.ResearchProject;
import cn.qidisoft.edu.hzjt.model.zyc.TeachingGroup;
import cn.qidisoft.edu.hzjt.service.zyc.IResearchProjectAuditingService;
import cn.qidisoft.edu.hzjt.utils.LogType;

/**
 * 
 * @author 课题审核控制层
 *
 */
@Controller
@RequestMapping("/researchProjectAuditing")
public class ResearchProjectAuditingController {
    protected static final LoggerAdapter    LOGGER = LoggerAdapterFactory
        .getLogger(LogType.HZJT_LOGGER.val);

    @Autowired
    private IResearchProjectAuditingService researchProjectAuditingService;

    //跳表格页面
    @RequestMapping("/index")
    public String index(ModelMap model,HttpServletRequest request) {
    	String type = request.getParameter("type");
    	request.getSession().setAttribute("type", type);
        // 获取部门信息
        List<Department> departments = researchProjectAuditingService.getDepartList();
        // 获取教研组信息
        List<TeachingGroup> teachingGroups = researchProjectAuditingService.getTeachList();
        model.addAttribute("departments", departments);
        model.addAttribute("teachingGroups", teachingGroups);
        return "zyc/researchProjectAuditing/list";
    }

    @RequestMapping(value = "/listData")
    @ResponseBody
    public ResponseResult sleResearchProjectAuditing(ModelMap model, HttpServletRequest request,
                                                     @RequestParam(value = "rows", required = false) String pageSize,
                                                     @RequestParam(value = "page", required = false) String currentPage,
                                                     ResearchProject researchProject) {
        try {
            Map<String, Object> queryMap = new HashMap<String, Object>();
            String empName = request.getParameter("empName");
            String subject = request.getParameter("subject");
            String kTLB = request.getParameter("kTLB");
            if (null != empName) {
                queryMap.put("empName", empName.trim());
            }
            if (null != subject) {
                queryMap.put("subject", subject.trim());
            }
            if (null != kTLB) {
                queryMap.put("kTLB", kTLB.trim());
            }
            queryMap.put("beginTime", request.getParameter("beginTime"));
            queryMap.put("endTime", request.getParameter("endTime"));
            Page page = new Page();
            page.setCurrPage(currentPage == null ? 0 : Integer.valueOf(currentPage));
            page.setPageSize(pageSize == null ? 10 : Integer.valueOf(pageSize));
            BaseController.setSortByColumn(request, "createTime", "asc");
            researchProject.setOrderField((String) request.getAttribute("orderField"));
            researchProject.setOrderFlag((String) request.getAttribute("orderFlag"));
            queryMap.put("researchProject", researchProject);
            PaginationBean<ResearchProject> paginationBean = researchProjectAuditingService
                .queryResearchProjectAuditingPageList(queryMap, page);
            ResponseResult result = new ResponseResult();
            result.setTotal(paginationBean.getTotalRecords());
            result.setRows(paginationBean.getPageList());
            return result;
        } catch (Exception e) {

        }
        return null;
    }

    /**
     * 课题审核下载
     * 
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "export_df")
    public @ResponseBody void export_dzb(HttpServletRequest request, HttpServletResponse response,
                                         ResearchProject researchProject) throws Exception {
        try {
            Map<String, Object> queryMap = new HashMap<String, Object>();
            String empName = request.getParameter("empName");
            String subject = request.getParameter("subject");
            String kTLB = request.getParameter("kTLB");
            if (null != empName) {
                queryMap.put("empName", empName.trim());
            }
            if (null != subject) {
                queryMap.put("subject", subject.trim());
            }
            if (null != kTLB) {
                queryMap.put("kTLB", kTLB.trim());
            }
            queryMap.put("researchProject", researchProject);
            queryMap.put("beginTime", request.getParameter("beginTime"));
            queryMap.put("endTime", request.getParameter("endTime"));
            List<ResearchProject> datalist = researchProjectAuditingService
                .queryResearchProjectAuditingList(queryMap);
            String[][] title_name = { { "课题Id", "标题", "类别", "时间", "进度", "提交人", "工号", "所在部门", "教研组",
                                        "提交时间" } };
            String[] title_style = { "hwzs_16_bold_25", "hwzs_16_bold_25", "hwzs_16_bold_25",
                                     "hwzs_16_bold_25", "hwzs_16_bold_25", "kt_12_bold_18",
                                     "kt_12_bold_18", "kt_12_bold_18", "kt_12_bold_18",
                                     "kt_12_bold_18" };
            String fileName = "课题审核";
            String[] remark = { "" };
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            if (datalist != null && !datalist.isEmpty()) {
                for (ResearchProject res : datalist) {
                    Map<String, Object> map = new LinkedHashMap<String, Object>();
                    map.put("kTID", res.getkTID());
                    map.put("subject", res.getSubject());
                    map.put("kTLB", res.getkTLB());
                    map.put("kTSJ", res.getkTSJ());
                    if (res.getCurStep() == 1) {
                        map.put("curStep", "填报课题");
                    }
                    if (res.getCurStep() == 2) {
                        map.put("curStep", "开题报告");
                    }
                    if (res.getCurStep() == 3) {
                        map.put("curStep", "中期报告");
                    }
                    if (res.getCurStep() == 4) {
                        map.put("curStep", "结题报告");
                    }
                    if (res.getCurStep() == 5) {
                        map.put("curStep", "研究过程及附件");
                    }
                    map.put("empName", res.getEmpName());
                    map.put("empId", res.getEmpId());
                    map.put("KSMC", res.getKSMC());
                    map.put("JYZMC", res.getJYZMC());
                    list.add(map);
                }
            }
            HSSFWorkbook wb = ExpExcelUtil.getWorkBookExcel(title_name, title_style, 100, remark,
                fileName, list);
            try {
                String filenameConvert = "课题审核";/* new String(fileName.getBytes("GB2312"), "ISO8859-1"); */
                response.reset();
                response.setContentType("application/vnd.ms-excel;charset=utf-8");
                response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String((filenameConvert + ".xls").getBytes(),
                        "iso-8859-1"));
                response.setDateHeader("Expires", 0);
                ServletOutputStream os = response.getOutputStream();
                wb.write(os);
                os.flush();
            } catch (Exception e) {
                System.out.println("网络连接断开，可能用户取消了导出");
            }
        } catch (RPCException e) {
            LOGGER.error(
                "获得xxxxx信息 exportStudentjobList [{}] error," + this.getClass().getName() + "=[{}]",
                this.getClass().getName(), e.getMessage());
        }
    }

}
